package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.model.ProductSku;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.CategoryVo;
import com.spzx.product.vo.IndexDataVo;
import com.spzx.product.vo.ItemVo;
import com.spzx.product.vo.ProductSkuVo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController  {
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private IBrandService brandService;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductDetailsService productDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
@Operation(summary = "首页数据")
    @GetMapping("/index")
    public AjaxResult indexData() {
        //1.创建首页VO对象
        IndexDataVo vo = new IndexDataVo();
        //2.封装一级分类列表
        List<CategoryVo> categoryVoList = categoryService.getLevelOneCategory();
        vo.setCategoryList(categoryVoList);

//        //3.封装畅销TOP20商品列表
        List<ProductSkuVo> productSkuList = productSkuService.selectTopSale();
        vo.setProductSkuList(productSkuList);

        //4.响应VO
        return AjaxResult.success(vo);
    }

@Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }

    @Operation(summary = "分页条件查询商品列表")
//若依分页有参的用这个
@GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(@PathVariable("pageNum") Integer pageNum
                               ,@PathVariable("pageSize") Integer pageSize
                                 ,SkuQuery skuQuery)
{
    PageHelper.startPage(pageNum,pageSize);
    List<ProductSkuVo> list=productSkuService.selectSkuList(skuQuery);
    return getDataTable(list);
}

@Operation(summary = "获取全部品牌")
@GetMapping("/brand")
    public AjaxResult selectBrandAll(){
    return success(brandService.list());
}

@Operation(summary = "封装商品sku详情页所需数据")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(@PathVariable("skuId") Long skuId){
    //TODO: 解决缓存穿透问题: 判断用户访问ID是否存在
    Boolean flag = redisTemplate.opsForValue().getBit("product:sku:data", skuId);
    if(!flag){
        throw new ServiceException("访问商品不存在");
    }
    //创建ItemVo对象
    ItemVo itemVo = new ItemVo();
//    //为ItemVo中七项属性逐一赋值
//    //根据商品SKUID查询商品SKU信息
//    ProductSku skuInfo = productSkuService.getSkuInfo(skuId);
//    itemVo.setProductSku(skuInfo);
//    //查询商品SKU价格,当价格产生变动,需要更新redis中的数据所以要再查一次
//    itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
//    //查询商品sku库存SkuStock
//    itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
//    //查询商品的轮播图列表
//    Long productId = skuInfo.getProductId();
//    Product product = productService.getById(productId);
//    if(product!=null && StringUtils.isNoneBlank(product.getSliderUrls())){
//        String sliderUrls = product.getSliderUrls();
//        itemVo.setSliderUrlList(sliderUrls.split(","));
//    }
//    //查询商品详情图片列表
//    ProductDetails productDetails = productDetailsService.getOne(new LambdaQueryWrapper<ProductDetails>()
//            .eq(ProductDetails::getProductId, productId));
//    if(productDetails!=null && StringUtils.isNoneBlank(productDetails.getImageUrls())){
//        itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
//    }
//    //查询规格信息,为了展示规格信息方便用户选择
//    String specValue = product.getSpecValue();
//    if( StringUtils.isNoneBlank(specValue)){
//        JSONArray jsonArray = JSON.parseArray(specValue);
//        itemVo.setSpecValueList(jsonArray);
//    }
//    //封装商品规格参数跟SKUID映射关系Map
//    itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
//    //响应ItemVo
//    return success(itemVo);

    //2.1 根据商品SKUID查询商品SKU信息  异步需要返回结果：商品SKU信息返回提供给 轮播图任务、详情图片任务、规格参数任务 使用
    CompletableFuture<Long> productIdCompletableFuture = CompletableFuture.supplyAsync(() -> {
        ProductSku skuInfo = productSkuService.getSkuInfo(skuId);
        itemVo.setProductSku(skuInfo);
        return skuInfo.getProductId();
    }, threadPoolExecutor);
    //2.2 查询商品SKU价格
    itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
    //2.3 查询商品SKU库存
    itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
    //2.4 查询商品轮播图列表  依赖商品ID异步任务，不需要有返回结果
    CompletableFuture<Void> imageCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
        Product product = productService.getById(productId);
        if (product != null && org.apache.commons.lang3.StringUtils.isNoneBlank(product.getSliderUrls())) {
            String sliderUrls = product.getSliderUrls();
            itemVo.setSliderUrlList(sliderUrls.split(","));
        }
        //2.5 查询商品详情图片列表
        ProductDetails productDetails = productDetailsService.getOne(
                new LambdaQueryWrapper<ProductDetails>()
                        .eq(ProductDetails::getProductId, productId)
        );
        if (productDetails != null && org.apache.commons.lang3.StringUtils.isNoneBlank(productDetails.getImageUrls())) {
            itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
        }
        //2.6 查询商品规格信息，展示规格信息用于用户选择
        String specValue = product.getSpecValue();
        if (StringUtils.isNoneBlank(specValue)) {
            JSONArray jsonArray = JSON.parseArray(specValue);
            itemVo.setSpecValueList(jsonArray);
        }
    }, threadPoolExecutor);
    //2.7 封装商品规格参数跟SKUID映射关系Map
    CompletableFuture<Void> skuSpecMapCompletableFuture = productIdCompletableFuture.thenAcceptAsync(productId -> {
        itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
    }, threadPoolExecutor);

    //3.阻塞线程，等待所有任务完成
    CompletableFuture
            .allOf(
                    productIdCompletableFuture,
                    imageCompletableFuture,
                    skuSpecMapCompletableFuture)
            .join();
    //3.响应ItemVo
    return success(itemVo);

}
}
